<template>
    <!-- 这里的rules为校验 -->
    <el-form ref="userRef" :model="form" :rules="rules" label-width="100px">

        <!-- prop都为验证使用,不加没有验证 -->
        <el-form-item label="用户名：" prop="username">
            <el-input v-model="form.username" maxlength="11"/>
        </el-form-item>
        <el-form-item label="手机号码：" prop="phonenumber">
            <el-input v-model="form.phonenumber" maxlength="11"/>
        </el-form-item>
        <el-form-item label="用户邮箱：" prop="email">
            <el-input v-model="form.email" maxlength="50"/>
        </el-form-item>
        <el-form-item>
            <!-- 提交保存事件 -->
            <el-button type="primary" @click="handleSubmit">保存</el-button>
        </el-form-item>
    </el-form>
</template>

<script setup>
import { defineProps } from 'vue';
import {ref} from 'vue'
import requestUtil from '@/utils/request';
import { ElMessage } from 'element-plus'
const props = defineProps({
    // 接收父组件传递的数据
    user: {
        // 类型
        type: Object,
        // 默认
        default: () => {

        },
        // 必填
        required: true
    }
})

const form = ref({
    id: -1,
    username:'',
    phonenumber: '',
    email: ''
})

// 定义userRef
const userRef = ref(null)
// 对表单数据进行初始化，即表单初始值
form.value = props.user;

// 手机号和邮箱校验规则
const rules = ref({
    username:[
        {required: true, message: "用户名不能为空", trigger: "blur"}],
    email: [
        {required: true, message: "邮箱地址不能为空", trigger: "blur"}, 
        {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"]
        }],
    phonenumber: [
        {required: true, message: "手机号码不能为空", trigger: "blur"}, 
        {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "手机号码格式有误",
            trigger: "blur"
        }],
});

// 用户修改提交
const handleSubmit = () => {
    // 先进行验证
userRef.value.validate(async (valid) => {
    // 判断是否为异步请求
    if (valid) {
        // 发起修改提交请求
        let result = await requestUtil.post("user/save", form.value);
        let data = result.data;
    if (data.code == 200) {
        ElMessage.success("执行成功！")
        // 更新后的数据
        window.sessionStorage.setItem("userInfo", JSON.stringify(form.value))
    }
    }
})
}
</script>

<style lang="scss">

</style>